
var groupheal = {
	textbox : {
		associatecheck : function (container, text) {
				container.focus(function(event) {
					if (container.val()===text) {
						container.val('');
					}
				});
			}
	},
	
	floatter : {
		status : 'hidden',
		show : function() {
			$('#floating').css("visibility", "visible");
		},
		hide : function() {
			$('#floating').css("visibility", "hidden");
		},
		changecontent : function(html) {
			var floatingdata = $('#floating-data');
			
			floatingdata.html(html);
		}
	},
	
	comment : {
		submit : function(event) {
			var data = $('#floating-data #commentform #comment').val();
			if(data !== "" && data !=='Enter a comment') {
				$.post('index.php?r=comment/post',
				   { data : data,
				     uri : window.location.pathname },
				     groupheal.floatter.hide);
			} else {
				groupheal.floatter.hide();
			}
		}
	},
	
	tooltip : {
		queue : [],
		dict : [],
		push : function(anchor, descrip, top, left, dict) {
			if (dict === '') {
				groupheal.tooltip.queue[groupheal.tooltip.queue.length] = [ anchor, descrip, top, left ];
				if(groupheal.tooltip.queue.length === 1) {
					groupheal.tooltip.next = groupheal.tooltip.queue[0];
				}
			} else {
				groupheal.tooltip.dict[dict] = [ anchor, descrip, top, left ];
			}
		},
		next : null,
		show : function() {
			if (groupheal.tooltip.queue.length === 0 || groupheal.tooltip.open ) {
				return;
			}
			groupheal.tooltip.open = true;
			var top = groupheal.tooltip.queue.shift();
			groupheal.tooltip.display(top);	
		},
		dictshow : function(id) {
			var top = groupheal.tooltip.dict[id];
			groupheal.tooltip.display(top, function() {
				$(top[1]).animate({'opacity' : 0}, 1000, 'linear');
			});
		},
		open : false,
		display : function(top) {
			var anchor = $(top[0]);
			var span = $(top[1]);
			
			var anchorleft = anchor.offset().left;
			var anchortop = anchor.offset().top;
			
			var anchorheight = anchor.height();
			var anchorwidth = anchor.width();
			span.css({ 'top': anchortop + top[2], 'left': anchorleft + top[3], 'display': 'block', 'opacity':0 });
			span.mouseover(function() {
				span.animate({'opacity': 0}, 200, 'linear', groupheal.tooltip.setnext);
			});
			span.animate({'opacity': 1}, 200, 'linear');
			setTimeout(function() {
				span.animate({'opacity': 0}, 200, 'linear', groupheal.tooltip.setnext);
			}, 5000);
		},
		setnext : function() {
			groupheal.tooltip.open = false;
			setTimeout(function() {
				groupheal.tooltip.show();
			}, 1000);
					
		}
	}
};

docalarm = {
 
    
    form : {
    	formtype : null,
    	outputcontainer : null,
    	codecontainer : null,
    	captcharesponse : function(data) {
    		//alert(data);
    		return;
    		var parsed = $.parseJSON(data);
    		var container = $(docalarm.form.outputcontainer+' #error');
    		if (parsed !== 'success') {
    		    var text = 'The following errors were detected:<br/>';
    		    for(var i in parsed) {
    		    	 text += '<br/>' + $("label[for='"+i+"']").attr('value')+": "+parsed[i];
    		    }
    		    container.html(text);
    		    container.slideDown(500);
    		} else {
    		    location.reload();
    		}
    		$(docalarm.form.outputcontainer+' #captcha').click();
    		$('#'+docalarm.form.formtype+'_VerifyCode').val("");
    	}
    },
    
	discussion : {
		load : function(event) {
			var identifier = event.currentTarget.id;
			docalarm.search.topbarminimize(function() {});
			$.post('/index.php?r=discussion/view', { page : identifier }, function(data) {
				$('#center').html(data);
         		$('#floating').css("visibility", "hidden");
			});
		}
	},
	
	settings : {
		selectedtypes : [],
		searchclick : function(event) {
			var identifier = event.currentTarget.id;
			docalarm.search.reset();
			var array = docalarm.settings.selectedtypes;
			if ($.inArray(identifier,array) === -1) {
				docalarm.search.append('general', identifier, 'right', 'docalarm.settings.remove', null);
				array[array.length] = identifier;
				$.post('/index.php?r=settings/addgroup', { id:identifier });
			}
			docalarm.settings.selectedtypes = array;
		},
		remove : function(event) {
			//alert('remove');
		}
	},
	
	eventrelation : {
		selecteddrugs : [],
		selecteddrugids : {},
		
		selectedaes : [],
		selectedaesids: {},
		
		selectioncutoff: 3,
		
		searchclick : function(event) {
			var identifier = event.currentTarget.id;
			docalarm.search.reset(identifier);
			var searchcontainer = $("#"+identifier);
			var preparsed_ids = searchcontainer.find('img').attr('id');
			var parsed_ids = $.parseJSON(preparsed_ids);
			var type = parsed_ids.t;
			parsed_ids = parsed_ids.i;

			var containerid = 'drugs';
			var discussioncolor = '#FF6600';
			var position = 'left';
			
			var array;
			
			if (type === 0) {
				array = docalarm.eventrelation.selecteddrugs;
			    for(entry in parsed_ids) {
			        var value = parsed_ids[entry];
			        var subarray = docalarm.eventrelation.selecteddrugids[value];
			        if (subarray === undefined) {
			            subarray = [identifier];    
			        } else if ($.inArray(identifier,subarray)===-1){
			            subarray[subarray.length] = identifier;
			        }
			        docalarm.eventrelation.selecteddrugids[value] = subarray;
			    }
			} else if (type === 1) {
			    containerid = 'aes';
				position = 'right';
				discussioncolor = '#00CC33';
			    
			    array = docalarm.eventrelation.selectedaes;
			    for(entry in parsed_ids) {
			        var value = parsed_ids[entry];
			        var subarray = docalarm.eventrelation.selectedaesids[value];
			        if (subarray === undefined) {
			            subarray = [identifier];    
			        } else if ($.inArray(identifier,subarray) === -1){
			            subarray[subarray.length] = identifier;
			        }
			        docalarm.eventrelation.selectedaesids[value] = subarray;
			    }
			}
			if ($.inArray(identifier,array) === -1) {
				docalarm.discussionlist.append(identifier, searchcontainer.find('#search-result-text').html(), discussioncolor, 2);
				docalarm.search.append(containerid, identifier, position, 'docalarm.entrysidebar', 'docalarm.search.itemclicked');
			    array[array.length] = identifier;
				if (type === 0) {
					docalarm.eventrelation.selecteddrugs = array;
				} else if (type === 1) {
					docalarm.eventrelation.selectedaes = array;
				}
			} else {
			    return;
			}
			
			
			docalarm.search.topbarminimize(function() {
				$.post(docalarm.baseUrl + '/index.php?r=association/change', { d: preparsed_ids }, 
				   	function(data) {
				   		docalarm.eventrelation.checkresponse(data, type, containerid, identifier);
				   	});
			});

			
			
		},
		
		buildconnection : function(value, pos, mypos, centerpos, identifier) {
			var spacing = 35;
			
	        var opacity = Math.abs(value) / docalarm.eventrelation.selectioncutoff;
            if (value >= docalarm.eventrelation.selectioncutoff) {
            	opacity = 1;
            } else if (opacity < .2) {
            	opacity = .2;
            }
            var linestring = "M"+
                (pos.left - centerpos.left + 2) + " " +
                (pos.top - centerpos.top + spacing - 2) + " L " +
                (mypos.left - centerpos.left + 298) + " " +
                (mypos.top - centerpos.top + spacing - 2);
            
            var result = docalarm.centercanvas.path(linestring);
            result.attr('stroke-width',2);
            result.attr('opacity', opacity);
            
            /*
            var lefttext = ((pos.left - centerpos.left + 298) + (mypos.left - centerpos.left + 2))/2;
            var toptext = ((mypos.top - centerpos.top + spacing - 2) + (pos.top - centerpos.top + spacing - 2))/2 - 13;
            var txt = docalarm.centercanvas.text(lefttext, toptext, Math.round(value * 100) / 100 );
            if( value > 1 ) { 
            	txt.attr({fill: "#f00", 'font-size': 20});
            } else {
            	txt.attr({fill: "#0f0", 'font-size': 20});
            }
            */
		},
		
		checkresponse : function(data, type, containerid, identifier) {
			
			var center = $('#result');
			docalarm.centercanvas.setSize(center.width()+'px', center.height()+'px');
			
			var centerpos = center.offset();
			var mypos = $('#' + containerid).find('#' + identifier).offset();
			var parsed_result = $.parseJSON(data);
			if (parsed_result.length !== 0) {
			    if (type === 0) {
			        for(entry in parsed_result) {
			        	var box = $('.entry').find('#'+entry);
				        var pos = box.offset();
			            docalarm.eventrelation.buildconnection(parsed_result[entry], pos, mypos, centerpos, identifier);   
			        }
			    } else {
			        for(entry in parsed_result) {
			        	var box = $('.entry').find('#'+entry);
			        	var pos = box.offset();
			        	docalarm.eventrelation.buildconnection(parsed_result[entry], mypos, pos, centerpos, identifier);   
			        }
			    }			
			}
			
			
		}
	},
	
	appointment : {
		datetime: null,
		datelinkclick : function(event) {
			docalarm.appointment.datetime = event.currentTarget.id;
			var content = $.get('/index.php?r=appointment/add', docalarm.appointment.addformload);
		},
		response : function(data) {
			if (data === 'success') {
				$.post('/index.php?r=appointment/view', {}, function(data) {
						$('#center').html(data);
						docalarm.floatter.hide();
					});
			} else {
				docalarm.form.captcharesponse(data);
			}
		},
		addformload : function(data) {
		
			var timecontainer = $('#' + docalarm.appointment.datetime);
			var timecontainerparent = timecontainer.parent();
			var content = '<div class="mdimg">' +
				timecontainerparent.parent().find('.mddescription .mdimg').html() +
				'</div> <div class="floatdescription"><p>' +
				timecontainerparent.find('.date').html() + ' ' +
				timecontainer.html() + 
				'<p>' +
				timecontainerparent.parent().find('.mddescription .mdtitle').html() +
				'</div>';
			docalarm.floatter.changecontent(content + data);
			docalarm.floatter.show();

			docalarm.form.type = 'AddAppointment';
			docalarm.form.outputcontainer = '#addappointment';
			
			
			$('#addappointment #newsubmit').click(function() {
				$.ajax({'success': docalarm.appointment.response,
						'type':'POST',
						'url':'/index.php?r=appointment/add&id=' + docalarm.appointment.datetime,
						'cache':false,
						'data':$("#addappointment-form").serialize()
					   });
			});
			
			$('#addappointment #captcha').click(function () {
				$.ajax({
					url: "\/index.php?r=appointment\/captcha&refresh=1",
					dataType: 'json',
					cache: false,
					success: function(data) {
						$('#yw0').attr('src', data['url']);
						$('body').data('captcha.hash', [data['hash1'], data['hash2']]);
					}
				});
			});
			
			$('#addappointment #captcha').click();
		},
	},
	
	patient : {
		prepareform : function(event) {
			var formsets = $('div.formset');
			var length = formsets.length;
			var data = [];
			for(var i = 0; i < length; i++) {
				var formset = $('div.formset#'+formsets[i].id);
				var tempdata = {id: formsets.attr('id'), selected:[]};
				var checked = formset.find('div.formsection div.choice input[type=radio]:checked');
				var checkedlength = checked.length;
				for(var j = 0; j < checkedlength; j++) {
					var split = checked[j].id.split('-');
					if (split[1][split[1].length-1] === '1') {
						tempdata.selected[tempdata.selected.length] = split[1].substr(0, split[1].length-1);
					}
				}
				data[data.length] = tempdata;
			}
			$.post('/index.php?r=patient/form', 
				   { data : data,
					 email : $('.patient #user').val() }, 
				   docalarm.patient.formresponse);
		},
		formresponse : function(data) {
			if(data==='success') {
				window.location = '/index.php';
			}//submitted
		}
	},
	
	doctor : {
		dateselected : function(dateText, inst) { 
			$.post('/index.php?r=doctor/appointment',
				  { t : dateText },
				  function (data) {
				  	$('#patientlist').html(data);
				  });
		},
		viewform : function(event) {
			window.location = '/index.php?r=doctor/viewform&id=' +
				event.currentTarget.id + 
				'&user=' +
				$('div.completed#'+event.currentTarget.id+' div.name').attr('id');
		},
		printform : function(event) {
			window.open('/index.php?r=doctor/viewformpdf&id=' +
				$('input[type=hidden]#id').val() +
				'&user=' +
				$('input[type=hidden]#username').val()
			);
			
		}
	},
	
	createform : {
		addform : function() {
			//alert($('#createforms #addforms').html());
			docalarm.floatter.changecontent($('#createforms #addforms').html());
			$('input#add').click(docalarm.createform.add);	
			$('#floating-data input.close').click(docalarm.floatter.hide);	
			docalarm.floatter.show();
		},
		add : function(event) {
			var container = $('#floating-data #newform');
			$.post('/index.php?r=doctor/addform',
				   { name : container.find('#name').val(), description : container.find('#description').val() },
				   docalarm.createform.addresponse);
		},
		addresponse : function(data) {
			//alert(data);
		},
		currentid: null,
		expand : function(event) {
			if (docalarm.createform.currentid !== event.currentTarget.id) {
				docalarm.createform.currentid = event.currentTarget.id;
				$.post('/index.php?r=doctor/formexpand',
					   {id : event.currentTarget.id},
					   docalarm.createform.expandresult);
				$('.expander').remove();
			}
		},
		expandresult : function(data) {
			var container = $('div.form#' + docalarm.createform.currentid);
			container.css('background-color', '#bbedfe');
			container.after(data);
			$('.expander input#additem').click(docalarm.createform.additem);
			$('.expander input#emailform').click(docalarm.createform.emailform);
		},
		emailform : function(event) {
			docalarm.floatter.changecontent($('#createforms #emailforms').html());
			$('#floating-data input#emailform').click(docalarm.createform.sendemail);	
			docalarm.floatter.show();
		},
		sendemail : function(event) {
			$.post('/index.php?r=doctor/emailform',
				   { email : $('#floating-data #email').val(), 
				   	 id: $('#forms .expander').attr('id')},
				   docalarm.createform.sendemailresponse);
			docalarm.floatter.hide();
		},
		sendemailresponse : function(data) {
			if (data === 'success') {
			} else {
			//	alert(data);
			}
		},
		additem : function() {
			docalarm.floatter.changecontent($('#createforms #choices').html());
			$('input#addlistitem').click(docalarm.createform.addlistinput.load);	
			docalarm.floatter.show();
		},
		addlistinput : {
			load : function() {
				docalarm.floatter.changecontent($('#createforms #holder-listinput').html());
				$('#floating-data #listinput #source').keypress(docalarm.createform.addlistinput.keypressadd);
				$('#floating-data #listinput #submitlistinput').click(docalarm.createform.addlistinput.add);
				$('#floating-data #listinput #saveform').click(docalarm.createform.addlistinput.save);
				$('#floating-data #listinput #name').focus(docalarm.createform.addlistinput.nameclear);
				docalarm.floatter.show();
			},
			save : function(event) {
				var formsets = $('#floating-data #listinput div.entry');
				var length = formsets.length;
				var data = [];
				for(var i = 0; i < length; i++) {
					data[data.length] = $('#floating-data #listinput div.entry#' + formsets[i].id + ' span.txt').html();
				}
				if (length > 0) {
					$.post('/index.php?r=doctor/formaddfield', 
						   { id : $('#forms .expander').attr('id'), 
						     title: $('#floating-data #listinput #name').val(),
						     items: data }, 
						   docalarm.createform.addlistinput.response);
				}
			},
			response : function(data) {
				//alert(data);
			},
			keypressadd : function(event) {
				if (event.which === 13) {
					docalarm.createform.addlistinput.add(event);
				}
			},
			add : function(event) {
				var stamp = event.timeStamp;
				$('#floating-data #listinput #entries').append(
					'<div class="entry" id="floating-' + stamp + '"><span class="txt">'+
					$('#floating-data #listinput #source').val() + 
					'</span><input class="close" type="button" id="floating-' + stamp +'"value="x"/></div>');
				$('input[type=button].close').click(docalarm.createform.addlistinput.remove);
				$('#floating-data #listinput #source').val('');
			},
			remove : function(event) {
				var id = event.currentTarget.id;
				$('div.entry#'+id).remove();
			},
			nameclear : function(event) {
				if ($('#floating-data #listinput #name').val() === 'Enter a name for the field') {
					$('#floating-data #listinput #name').val('');
				}
			}
		}
		
	},
	
	floatter : {
		status : 'hidden',
		show : function() {
			$('#floating').css("visibility", "visible");
		},
		hide : function() {
			$('#floating').css("visibility", "hidden");
		},
		changecontent : function(html) {
			var floatingdata = $('#floating-data');
			
			floatingdata.html(html);
		}
	},
	
	discussionlist : {
		append : function(identifier, text, textcolor, emcount) {
			$('#index-discussList').append('<li class="newlist"><a href="/index.php?r=discussion/view&page=' +
										   identifier + '"><em><em>' + 
										   text + '</em></em></a></li>').
									find('li:last').css({display:"none", color:textcolor}).fadeIn(1000);	
		}
	},
	entrysidebar : function(event) {
		$.post('index.php?r=association/remove&' + event.currentTarget.id,
				function() {
			   		window.location = 'index.php?r=association/view&m=1';
				});
	},
	search : {
		
		itemclicked: function(event) {
			window.location = 'index.php?r=discussion/view&page='+event.currentTarget.id;
		},
		reset : function() {
			var searchbox = $("#searchBox");
			searchbox.val(docalarm.searchText);
			docalarm.search.notclicked = true;
		}, 
		append: function(container, identifier, position, buttonclick, itemclick) {
			var text = "<div class='entry'>";
			if (buttonclick === null) {
				text += "<div class='button " + position + "' id='rm=" + identifier + "'></div>";
			} else {
				text += "<div class='button " + position + "' id='rm=" + identifier + "' onclick='" + buttonclick + "(event);'></div>";
			}
			if (itemclick === null) {
				text += "<div class='entry-main'>";
			} else {
				text += "<div class='entry-main' id='" + identifier + "' onclick='" + itemclick + "(event);'>";
			}
			text += $('#'+identifier).html() + "</div></div>"
			$('#'+container).append(text);	
		},
		topbarminimize : function(func) {
		    if(docalarm.search.clickedonce === false) {
		    	$('div#search').animate({ 'top': '5px', 'left': '5px', 'height': '20px', 'width': '310px'}, 
		    	      {  duration: 'medium',// how fast we are animating
		    				  complete: function() { // the callback
		    				    $('div#logo img').animate({height: '30px', width:'120px'});
		    				    
		    				    $('div#logo').
		    				    	animate({ 'top': '2px', 'left': '0px', 'height': '35px', 'width': '120px'}, 
		    				    		    { duration: 'medium', 
			    					         complete: function() {
			    					         	$('#topbar').animate({'height': '35px'}, {duration:'slow'});
			    					       	 	$('#header').animate({'height': '35px'}, {duration:'slow', 
			    					       	 		complete: function() {
			    					       	 			func();
			    					       	 			docalarm.search.reset();
			    					       	 		}
			    					       	 	});
			    					       	 	
			    					       	 	}
			    					       	 	
			    					       	 });
		    						      }
		    						  });
	
		    	docalarm.search.clickedonce = true;   	
		    } else {
		    	func();
		    	docalarm.search.reset();
		    }
		},
		clickedonce: false,
		notclicked : true
    },
    
    centercanvas : null,
    
    
    
    clickedonce: false,
        
    
    canvasdata : {},    
    discussionpage : null,
    discussionpageload : function(pageid) {
        docalarm.discussionpage = pageid;
        
        var discussion = $('#discussion');
        
        var textarea = $('#discussion textarea')
        var settext = false;
        textarea.click(function() {
            if (settext === false ) {
                textarea.text("");
                settext = true;
            }
        });
        
        var postbutton = discussion.find('.addpost');
        postbutton.click(docalarm.addpost);
        $('#floating').css("visibility", "visible");
    },
    
    addcomment : function(event) {
        var floatingdata = $('#floating-data');
        floatingdata.html('<div class="title">What do you want to add to the discussion?</div>' +
             '<textarea class="inputtext" >Please type your comment here.</textarea>' +
             '<input type="button" class="addpost" value="POST">' +
             '<div class="clear"></div>'
             );
        var floatingtextarea = floatingdata.find('textarea');
        var settext = false;
        floatingtextarea.click(function() {
            if (settext === false ) {
                floatingtextarea.text("");
                settext = true;
            }
        });
        var postbutton = floatingdata.find('.addpost');
        postbutton.attr("id", event.currentTarget.id);
        postbutton.click(docalarm.addpost);
        $('#floating').css("visibility", "visible")
    },
    
    addpost : function(event) {
        var text = null;
        var id = event.currentTarget.id;
        if (id === 'post') {
    	    text = $('#discussion textarea').val();
    	    id = '';
    	} else {
            text = $('#floating-data textarea').val();
        }
        $.post(docalarm.baseUrl + '/index.php?r=discussion/post', 
            {
                page: docalarm.discussionpage,
                pp: id,
                txt: text
            }, function(data) {
                $('#center').html(data);
         		$('#floating').css("visibility", "hidden")
            });
         
        if (id !== 'page') {
            text = $('#floating-data textarea').val();
         } else {
            text = $('#discussion textarea').val();
            $('#discussion textarea').text('Please type your comment here');
        }
    },
    
    floatinghide : function(event) {
        $('#floating').css("visibility", "hidden")    
    }, 
    
    loggedinmainload : function() {
        $('#floating-dimming').click(docalarm.floatinghide);
    
    },
    
    associatepost :function() {
        $('#discussion .postbutton').click(docalarm.addcomment);
    },
    
    searchnotclicked : true,
    baseUrl : null,
    pageType: null,
    searchUrl : null,
    searchText : 'Enter a Discussion Topic',
    
    finalizePage : function () {
    	if (docalarm.searchUrl === null) {
    		docalarm.searchUrl = '/index?r=discussion/search';
    	}
        var searchbox = $("#searchBox");
        searchbox.focusin(function () {
            if (docalarm.search.notclicked === true) {
                $("#searchBox").val('');
                docalarm.search.notclicked = false;
            }
        });
        
        var suggestions = $('#suggestions');
        
        searchbox.keyup(function (event) {
            var inputstring = searchbox.val();    
            if(inputstring.length === 0) {
                suggestions.fadeOut(); // Hide the suggestions box
            } else {
                $.post(docalarm.baseUrl+docalarm.searchUrl,
                    {    
                        pageType: docalarm.pageType, 
                        data: inputstring
                    }, function(data) {
                        suggestions.html(data);
                        suggestions.fadeIn();
                    }
                );
            }
        });
            
        $('html').click(function(e){
            suggestions.fadeOut(); // Hide the suggestions box
        });
        
                
    },
    
}
